package cn.clq.ssmshiro.realm;

import cn.clq.ssmshiro.dao.UserDao;
import cn.clq.ssmshiro.pojo.User;
import cn.clq.ssmshiro.util.JedisUtil;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import javax.annotation.Resource;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 检验登陆用户是否具有权限
 */
public class CustomRealm extends AuthorizingRealm{ //授权realm

    @Resource
    private UserDao userDao;

    /**
     * 已经开启了缓存机制，不需要每次都读取
     * @param principals
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        String username = (String) principals.getPrimaryPrincipal();
        Set<String> set= getRolesByUsername(username);
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        authorizationInfo.setRoles(set);
        return authorizationInfo;
    }

    private Set<String> getRolesByUsername(String username) {
        Set<String> set = new HashSet<>();
        List<String> list= userDao.getRolesByUsername(username);
        for(String role : list){
            set.add(role);
        }
        return set;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String username = (String) token.getPrincipal();
        String password = getPasswordByUsername(username);
//        System.out.println(username+","+password);
        if(password==null){
            return null;
        }
        AuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(username,password,"customRealm");
        return authenticationInfo;
    }

    /**
     * 从数据库获取用户信息
     * @param username
     * @return
     */
    private String getPasswordByUsername(String username) {
        if (username==null)
            return null;
        User user = userDao.getUserByUsername(username);
        return user.getPassword();
    }

}
